package cn.yudao.ymcc.mq.comsumer;


import cn.yudao.ymcc.domain.MessageSms;
import cn.yudao.ymcc.domain.User;
import cn.yudao.ymcc.dto.OnLineSmsDto;
import cn.yudao.ymcc.service.IMessageSmsService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@RocketMQMessageListener(consumerGroup="service-common-consumer-sms",
        topic="topic-online",
        selectorExpression="rag-sms",
        messageModel = MessageModel.CLUSTERING) // 默认是集群 1个消息被一个消费者消费 MessageModel.BROADCASTING 广播 1个消息被所有的消费者消费
public class OnLineSmsConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;


    @Override
    public void onMessage(MessageExt message) {

        // 拿到对象
        byte[] body = message.getBody();
        OnLineSmsDto onLineSmsDto = JSONObject.parseObject(body, OnLineSmsDto.class);
        // 添加到发送短信日志
        ArrayList<MessageSms> messageSms = new ArrayList<>();
        List<User> users = onLineSmsDto.getUsers();
        users.stream().map(user -> {
            MessageSms messageSms1 = new MessageSms();
            messageSms1.setPhone(user.getPhone());
            messageSms1.setUserId(user.getId());
            messageSms1.setTitle("新课程上架通知");
            messageSms1.setSendTime(new Date());
            messageSms1.setContent("亲爱的用户，本网站有新课程上架,新课程详情的网址为 还没有写");
            messageSms.add(messageSms1);
            // 调用发送短信
            System.out.println("亲爱的用户，本网站有新课程上架,新课程详情的网址为 还没有写" + user.getPhone());
            return messageSms1;
        }).count();
        // 批量新增
        messageSmsService.insertBatch(messageSms);

    }

}
